<script setup>
import { ref, onMounted } from 'vue';
import { Maintain_Image } from '@/api';

let props = defineProps({
    modelValue: {
        type: String,
    },
    is_show: {
        type: Boolean,
        default: false,
    },
    action: {
        type: String,
        default: 'http://www.shop.net/adminapi/file/upload',
    },
    pid: {
        type: Number,
        default: 0,
    },
});

let headers = ref({})
onMounted(() => {
    headers.value = { 'Authori-zation': sessionStorage.token };
    handleSelectIcon();
})

// 宏函数：声明event事件
// update:和modelValue中间不能有空格！！！
let emit = defineEmits(['update:modelValue', 'change', 'selected']);

// 选择图标
let activeName = ref('')
let iconData = ref([])
let sift_icon = ref(null)
let selectedIds = ref([])
let totalIcon = ref([])
let changeImg = ref('')
let select_icon_visible = ref(false)
let handleSelectIcon = async () => {
    // 分类列表
    let { status, msg, data } = await Maintain_Image.cate_list();
    // 图标列表
    let { status: iconStatus, data: icon } = await Maintain_Image.file_list({ pid: 0, page: 1, limit: 18 });
    if (status === 200 && iconStatus === 200) {
        iconData.value = data.list;
        totalIcon.value = icon.list;
        total.value = icon.count;
        select_icon_visible.value = true;
    }
}
let toggleSelection = (item) => {
    if (isSelected(item.att_id)) {
        // 如果已经选中，取消选中并从数组中删除
        let index = selectedIds.value.indexOf(item.att_id)
        if (index !== -1) {
            selectedIds.value.splice(index, 1)
        }
    } else {
        // 如果未选中，添加到数组中
        selectedIds.value.push(item.att_id)
        changeImg.value = item.att_dir;
    }

}
let isSelected = (id) => {
    // 判断 ID 是否在数组中
    return selectedIds.value.includes(id)
}

// 使用选中图片
let handleChangeImg = () => {
    if (selectedIds.value.length >= 2) {
        ElMessage.error("最多只能选一张图片！");
    } else {
        let photo = changeImg.value;
        emit('update:modelValue', photo);
        emit('change', photo);
    }
}

// 删除图片
let handleRemoveImg = () => {
    ElMessageBox.confirm(
        '确定要删除选中的图片？',
        '删除选中的图片',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            let ids = selectedIds.value.toString();
            let { status, msg } = await Maintain_Image.file_del({ ids });
            if (status === 200) {
                let { status, data } = await Maintain_Image.file_list({ pid: 0, page: 1, limit: 18 });
                if (status === 200) {
                    totalIcon.value = data.list;
                    total.value = data.count;
                    selectedIds.value = [];
                    ElMessage.success(msg);
                }
            } else {
                ElMessage.error(msg);
            }
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消成功',
            })
        })
}

// 关闭
let hangleEditIconClose = () => {
    selectedIds.value = [];
    emit('change');
}

// 分页
let total = ref(0)
let currentPage = ref(1)
let pageSize = ref(18)
let handleCurrentChange = async (page) => {
    let { status, msg, data } = await Maintain_Image.file_list({ pid: pid.value, page: page, limit: 18 });
    if (status) {
        totalIcon.value = data.list;
    } else {
        ElMessage.error(msg);
    }
}

// 分类切换
let pid = ref('')
let handleTabsChange = async (tab) => {
    pid.value = JSON.parse(JSON.stringify(tab.props.name));
    let { status, msg, data } = await Maintain_Image.file_list({ page: 1, limit: 18, pid: pid.value });
    if (status === 200) {
        currentPage.value = 1;
        totalIcon.value = data.list;
        total.value = data.count;
    }
}

// 搜索分类
let search_cate = ref('')
let handleSearchCate = async () => {
    let { status, msg, data } = await Maintain_Image.cate_list({ name: search_cate.value });
    if (status === 200) {
        iconData.value = data.list;
    } else {
        ElMessage.error(msg);
    }
}

// 上传成功
let handleUpSuccess = async (val) => {
    let { status, msg } = val;
    if (status === 200) {
        let { status, data } = await Maintain_Image.file_list({ pid: 0, page: 1, limit: 18 });
        if (status === 200) {
            totalIcon.value = data.list;
            total.value = data.count;
            ElMessage.success(msg);
        }
    }
}
// 上传失败
let handleUpError = (val) => {
    let { status, msg } = val;
    ElMessage.error(msg);
}

// 移动图片
let handlePhotoMove = async (val) => {
    let images = selectedIds.value.toString();
    if (!images) {
        ElMessage.warning('请选择要移动的图片！');
        sift_icon.value = null;
    } else {
        let { status, msg } = await Maintain_Image.set_file_cate({ pid: val, images })
        if (status === 200) {
            selectedIds.value = [];
            sift_icon.value = null;
            ElMessage.success(msg);
        } else {
            ElMessage.error(msg);
        }
    }
}

</script>

<template>
    <!-- 选择图片 -->
    <el-dialog :model-value="is_show" title="请选择图标" width="70%" @close="hangleEditIconClose">
        <div class="icon-select">
            <div class="select-cate">
                <el-input v-model="search_cate" placeholder="请输入分类名称" style="width: 200px;margin-bottom: 20px;"
                    class="input-with-select">
                    <template #append>
                        <el-button icon="Search" @click="handleSearchCate" />
                    </template>
                </el-input>
            </div>
            <div class="up-btn">
                <el-button type="primary" :disabled="selectedIds.length ? false : true"
                    @click="handleChangeImg">使用选中图片</el-button>
                <el-upload class="upload-demo" :show-file-list="false" :action="action" :headers="headers" multiple
                    :limit="3" :on-success="handleUpSuccess" :on-error="handleUpError" :data="{ pid: 0 }">
                    <el-button type="primary">上传图片</el-button>
                </el-upload>
                <el-button type="danger" style="margin-right: 15px;" :disabled="selectedIds.length ? false : true"
                    @click="handleRemoveImg">删除图片</el-button>
                <el-select v-model="sift_icon" :value="sift_icon" class="m-2" placeholder="图片移动至" @change="handlePhotoMove">
                    <el-option label="全部图片" value="" />
                    <el-option v-for="item in iconData" :key="item.id" :label="item.title" :value="item.id" />
                </el-select>
            </div>
        </div>
        <el-tabs v-model="activeName" tab-position="left" class="demo-tabs" @tab-click="handleTabsChange">
            <el-tab-pane label="全部图片" name=""></el-tab-pane>
            <el-tab-pane v-for="icon in iconData" :key="icon.id" :label="icon.title" :name="icon.id"></el-tab-pane>
            <div class="total-icons">
                <div v-for="item in totalIcon" @click="toggleSelection(item)" class="only-icon"
                    :class="{ selected: isSelected(item.att_id) }">
                    <el-badge :value="selectedIds.indexOf(item.att_id) >= 0 ? selectedIds.indexOf(item.att_id) + 1 : ''">
                        <el-image style="width: 100px; height: 100px" :src="item.satt_dir" fit="fill"
                            :title="item.real_name" />
                    </el-badge>
                    <div class="img-title">{{ item.real_name }}</div>
                </div>
            </div>
        </el-tabs>
        <div class="icon-page">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" background
                layout="total, prev, pager, next, jumper" :total="total" @current-change="handleCurrentChange" />
        </div>
    </el-dialog>
</template>

<style lang="less" scoped>
.avatar-uploader .avatar {
    width: 50px;
    height: 50px;
    display: block;
    border: 1px solid #ccc;
}

.icon-select {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;

    .up-btn {
        display: flex;

        .el-button {
            margin-right: 15px;
        }
    }

}

.demo-tabs {

    .total-icons {
        display: flex;
        flex-wrap: wrap;
        justify-content: flex-start;
        align-items: center;

        .only-icon {
            width: 100px;
            border: 2px solid transparent;
            margin: 5px 20px 5px 20px;

            .img-title {
                font-size: 10px;
                text-align: center;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
            }
        }

        .selected {
            border-width: 2px;
            border-color: #5fb878;
        }
    }
}

.icon-page {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 18px;
    color: #8c939d;
    width: 50px;
    height: 50px;
    text-align: center;
}
</style>